{extend name='common/common' /}

{block name="style"}
<style type="text/css">
#container{
    padding: 15px;
}
#editor {
    position: absolute;
    top: 0;left: 0;right: 0;bottom: 0;
}
#codeEditor{
    position: relative;
    width: 80%;
    height: 700px;
    float: left;
}
#toolBar{
    height: 50px;
    padding: 10px;
    border: 2px solid #3D3E3F;
    background-color: #FFF;
}
#toolBar label,#toolBar select {
    line-height: 30px;
    height: 30px;
}
#toolBar button {
    float:right;
    margin-left:10px;
}
#testView{
    float: left;
    height: 700px;
    width: 0;
    background-color: #676a6c;
}
#FileView{
    float: left;
    height: 700px;
    width: 20%;
    background-color: #2f4050;
    overflow: auto;
}
#ResizeBtn{
    width: 2px;
    /*background-color: #5cb85c;*/
    background-color: #333;
    position: absolute;
    z-index: 999999;
    cursor: e-resize;
}
#HideViewBtn{
    width: 30px;
    height: 50px;
    line-height: 50px;
    color:#FFF;
    text-align: center;
    font-size: 24px;
    background-color: #5cb85c;
    position: absolute;
    z-index: 999999;
    cursor: pointer;
    border-radius: 15px;
    transition: all 0.3s;
    right: -30px;
    top: 50px;
    opacity: 0;
}

#MarkDownView{
    width: 80px;
    height: 150px;
    position: absolute;
    z-index: 999998;
    border-radius: 50px 0 0 50px ;
    overflow: hidden;
}
#MarkDownView:hover #HideViewBtn{
    opacity: 1;
    right:0;
}
#ResizeFileBtn{
    width: 2px;
    background-color: #333;
    position: absolute;
    z-index: 999999;
    cursor: e-resize;
}
.layui-tree li a i {
	color:#a7b1c2;
}
.layui-tree li a cite {
	color:#a7b1c2;
}
.layui-tree li i{
	color:#a7b1c2;
}

#FileOncontextmenu{
	display: none;
}
.layui-elem-quote{
	font-size: 14px;
	padding: 5px;
	margin-bottom: 2px;
	border-left: 0;
}
.layui-elem-quote:hover{
	border-left: 5px solid #09F;
	cursor: pointer;
}
#NewFolderAskBox{
	display: none;
	padding: 15px;
}
#DeleteAskBox{
	display: none;
}
#RenameAskBox{
	display: none;
	padding: 15px;
}
#testViewIframe{
	border: 0;
	background-color: #FFF;
}
#resizeMark{
	position: absolute;
	z-index: 999995;
	width: 130px;
	display: none;
}
</style>
{/block}

{block name="content"}
<div id="container">
            <div id="toolBar">
                <label>Languages:</label>
                <select id="selectLanguage">
                    <option value="javascript">JS</option>
                    <option value="php">PHP</option>
                    <option value="html">HTML</option>
					<option value="css">css</option>
                    <option value="java">Java</option>
                    <option value="python">Python</option>
                    <option value="c_cpp">C_cpp</option>
                    <option value="r">R</option>
                    <option value="ruby">Ruby</option>
                    <option value="sql">Sql</option>
                    <option value="sh">Sh</option>
                    <option value="text">Text</option>
                </select>
                <label>Themes:</label>
                <select id="selectTheme">
                    <option value="monokai">monokai</option>
                    <option value="clouds">clouds</option>
                    <option value="terminal">terminal</option>
                    <option value="dreamweaver">dreamweaver</option>
                    <option value="github">github</option>
                    <option value="chrome">chrome</option>
                    <option value="twilight">twilight</option>
                    <option value="chaos">chaos</option>
                    <option value="ambiance">ambiance</option>
                    <option value="clouds_midnight">clouds_midnight</option>
                    <option value="cobalt">cobalt</option>
                    <option value="tomorrow">tomorrow</option>
                    <option value="tomorrow_night">tomorrow_night</option>
                    <option value="xcode">xcode</option>
                    <option value="sqlserver">sqlserver</option>
                </select>
                <label>FontSize:</label>
                <select id="selectFTsize">
                    <option value="13">13px</option>
                    <option value="14">14px</option>
                    <option value="15">15px</option>
                    <option value="16">16px</option>
                    <option value="17">17px</option>
                    <option value="18" selected>18px</option>
                    <option value="19">19px</option>
                    <option value="20">20px</option>
                    <option value="21">21px</option>
                    <option value="22">22px</option>
                    <option value="23">23px</option>
                    <option value="24">24px</option>
                    <option value="32">32px</option>
                    <option value="48">48px</option>
                    <option value="60">60px</option>
                    <option value="72">72px</option>
                </select>
                <button id="run" class="btn btn-success btn-sm">Run</button>
                <button id="BackToIndex" class="btn btn-danger btn-sm">Back</button>
                <button id="saveCode" class="btn btn-primary btn-sm">Save</button>
            </div>
            <div id="FileView">
            	<ul id="tree"></ul>
            </div>
            <div id="codeEditor"></div>
            <div id="testView">
				<iframe src="{:url('index/index/index')}" width="100%" height="100%" id="testViewIframe"></iframe>
			</div>
			<div id="resizeMark"></div>
            <div id="ResizeBtn"></div>
            <div id="ResizeFileBtn"></div>
            <div id="MarkDownView"><div id="HideViewBtn"><</div></div>
        </div>
		<input type="hidden" id="nowFilePath" name="path" value="">
		<!-- contextmenu -->
		<div id="FileOncontextmenu">
			<ul>
				<blockquote id="NewFolder" class="layui-elem-quote">New Folder</blockquote>
				<blockquote id="NewFile" class="layui-elem-quote">New File</blockquote>
				<blockquote id="DeleteFolder" class="layui-elem-quote">Delete Folder</blockquote>
				<blockquote id="DeleteFile" class="layui-elem-quote">Delete File</blockquote>
				<blockquote id="RenameFolderOrFile" class="layui-elem-quote ">Rename</blockquote>
			</ul>
		</div>
		<!-- contextmenu -->

		<!-- ask for NewFolder -->
		<div id="NewFolderAskBox">
			<form class="layui-form" action="" method="post" id="NewFolderForm">
				<div class="layui-form-item">
					<label class="layui-form-label">Name:</label>
					<div class="layui-input-block">
						<input type="text" name="name" placeholder="请输入" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">BelongsTo:</label>
					<div class="layui-input-block">
						<ul id="NewTree"></ul>
						<input type="hidden" name="path" id="NewFloderPath">
					</div>
				</div>
			</form>
		</div>
		<!-- ask for NewFolder -->

		<!-- ask for Delete -->
		<div id="DeleteAskBox">
			<div class="layui-form-item">
				<div class="layui-input-block">
					<ul id="DeleteTree"></ul>
				</div>
			</div>
		</div>
		<!-- ask for Delete -->

		<!-- ask for Rename -->
		<div id="RenameAskBox">
			<form class="layui-form" action="" method="post" id="RenameForm">
				<div class="layui-form-item">
					<label class="layui-form-label">Name:</label>
					<div class="layui-input-block">
						<input type="text" name="name" placeholder="请输入" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">Which:</label>
					<div class="layui-input-block">
						<ul id="RenameTree"></ul>
						<input type="hidden" name="path" id="RenamePath">
					</div>
				</div>
			</form>
		</div>
		<!-- ask for Rename -->

		<input type="hidden" id="NewType" value="0">
		<input type="hidden" id="DeleteType" value="0">
{/block}


{block name="script"}
<script src="__JS__/ide/src/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="__JS__/ide/src/ext-language_tools.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
    function rendEditor(language="javascript",theme="monokai",ftsize=18){
        ftsize = Number(ftsize);
        editor = ace.edit("editor");//初始化对象
        editor.setTheme("ace/theme/" + theme);//主题
        editor.session.setMode("ace/mode/" + language);//语言类型
        editor.setFontSize(ftsize);//字体大小
        editor.setReadOnly(false); //设置只读（true时只读，用于展示代码）
        editor.setOption("wrap", "free");//自动换行,设置为off关闭
        //代码提示
        ace.require("ace/ext/language_tools");
        editor.setOptions({
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true
        });
        // var code = editor.getValue();//获取代码
        // console.log(code);
    }
    $(function(){
        // 初始化样式
        var oTestView = document.getElementById('testView');
        var oFileView = document.getElementById('FileView');
        var codeEditor = document.getElementById('codeEditor');
        var containerPadding = 30;
        var WindowWidth = window.innerWidth - containerPadding;
        var toolBar = document.getElementById('toolBar');
        oTestView.style.height = window.innerHeight - 90 + "px";
        oFileView.style.height = oTestView.style.height;
        codeEditor.style.height = oTestView.style.height;
        $("#ResizeBtn").hide();
        $("#MarkDownView").css({
            'left':codeEditor.offsetWidth - 70 + oFileView.offsetWidth + 'px',
            'top':Math.floor((codeEditor.offsetHeight - 40)/2) + 'px'
        });
        $("#ResizeBtn").css({
            'left':codeEditor.offsetWidth + oFileView.offsetWidth + 13 +"px",
            'height':codeEditor.offsetHeight + 'px'
        });
        $("#ResizeFileBtn").css({
            'left':oFileView.offsetWidth + 15 + "px",
            'height':codeEditor.offsetHeight + 'px'
        });

        //初始化代码、编辑器
        var initCode = "console.log('version = 1.04');";
        var html = '<div id="editor"><textarea>'+initCode+'</textarea></div>';
        codeEditor.innerHTML = html;
        rendEditor($("#selectLanguage").val(),$("#selectTheme").val(),$("#selectFTsize").val());




        //切换语法
        $("#selectLanguage").on('change',function(){
            rendEditor($("#selectLanguage").val(),$("#selectTheme").val(),$("#selectFTsize").val());
        });
        //切换主题
        $("#selectTheme").on('change',function(){
            rendEditor($("#selectLanguage").val(),$("#selectTheme").val(),$("#selectFTsize").val());
        });
        //切换字体大小
        $("#selectFTsize").on('change',function(){
            rendEditor($("#selectLanguage").val(),$("#selectTheme").val(),$("#selectFTsize").val());
        });

        window.onresize = function (){
            WindowWidth = window.innerWidth - containerPadding;
            oTestView.style.height = window.innerHeight - 90 + "px";
            codeEditor.style.height = oTestView.style.height;
            oFileView.style.height = oTestView.style.height;
            if(oTestView.offsetWidth != 0 && oFileView.offsetWidth != 0){
                codeEditor.style.width = Math.floor(0.6 * toolBar.offsetWidth) + 'px';
                oTestView.style.width = Math.floor(0.2 * toolBar.offsetWidth) +'px';
                oFileView.style.width = Math.floor(0.2 * toolBar.offsetWidth) +'px';
            }
            if(oFileView.offsetWidth != 0 && oTestView.offsetWidth == 0){
                codeEditor.style.width = Math.floor(0.8 * toolBar.offsetWidth) + 'px';
                oFileView.style.width = Math.floor(0.2 * toolBar.offsetWidth) +'px';
            }
            $("#ResizeBtn").css({
                'left':codeEditor.offsetWidth + 13 + oFileView.offsetWidth + "px",
                'height':codeEditor.offsetHeight + 'px'
            });
            $("#ResizeFileBtn").css({
                'left':oFileView.offsetWidth + 15 + "px",
                'height':codeEditor.offsetHeight + 'px'
            });
            $("#MarkDownView").css({
                'left':codeEditor.offsetWidth - 70 + oFileView.offsetWidth + 'px',
                'top':Math.floor((codeEditor.offsetHeight - 40)/2) + 'px'
            });
        }

        // resize视图、编辑器
        var oResizeTestViewBtn = document.getElementById('ResizeBtn');
        var disX=0;
        oResizeTestViewBtn.onmousedown=function(ev){
            $("#MarkDownView").hide();
			$("#resizeMark").css({
				'left':oTestView.offsetLeft+'px',
				'height':codeEditor.offsetHeight+'px',
				'width':oTestView.offsetWidth + 'px'
			});
			$("#resizeMark").show();
            var oEvent=ev||event;
            disX=oEvent.clientX-oResizeTestViewBtn.offsetLeft;//鼠标和div左上角的距离
            document.onmousemove=function(ev){
				$("#resizeMark").css({
					'left':oTestView.offsetLeft+'px',
					'height':codeEditor.offsetHeight+'px',
					'width':oTestView.offsetWidth + 'px'
				});
                var oEvent=ev||event;
                var lt=oEvent.clientX-disX;//鼠标坐标减去距离得到div的位置坐标
                if(lt<500 + oFileView.offsetWidth){
                    lt=500 + oFileView.offsetWidth;
                }
                else if(lt>document.documentElement.clientWidth-oResizeTestViewBtn.offsetWidth-150){
                    lt=document.documentElement.clientWidth-oResizeTestViewBtn.offsetWidth-150;
                }
                codeEditor.style.width = lt - 13 - oFileView.offsetWidth +'px';
                $('#testView').css({'width': WindowWidth - lt + 13 + 'px'});

                oResizeTestViewBtn.style.left=lt+'px';
            }
            document.onmouseup=function(){
                document.onmousemove=null;
                document.onmouseup=null;
                $("#MarkDownView").show();
                $("#MarkDownView").css({
                    'left':codeEditor.offsetWidth - 70 + oFileView.offsetWidth + 'px',
                    'top':Math.floor((codeEditor.offsetHeight - 40)/2) + 'px'
                });
				$("#resizeMark").css({
					'width':'0 px'
				});
				$("#resizeMark").hide();
                rendEditor($("#selectLanguage").val(),$("#selectTheme").val(),$("#selectFTsize").val());
            }
            return false;
        }
        // resize文件、编辑器
        var oResizeFileBtn = document.getElementById('ResizeFileBtn');
        var disX_F=0;
        oResizeFileBtn.onmousedown=function(ev){
            if(Toggle%2 != 0){
                $("#HideViewBtn").click();
            }
            var oEvent=ev||event;
            disX_F=oEvent.clientX-oResizeFileBtn.offsetLeft;//鼠标和div左上角的距离
            document.onmousemove=function(ev){

                var oEvent=ev||event;
                var lt=oEvent.clientX-disX_F;//鼠标坐标减去距离得到div的位置坐标
                if(lt<100){
                    lt=100;
                }
                else if(lt>document.documentElement.clientWidth-oResizeFileBtn.offsetWidth-500- oTestView.offsetWidth){
                    lt=document.documentElement.clientWidth-oResizeFileBtn.offsetWidth-500- oTestView.offsetWidth;
                }
                oFileView.style.width = lt - 15 +'px';
                $('#codeEditor').css({'width': WindowWidth - (lt - 15) + 'px'});
                $("#ResizeBtn").css({'left':codeEditor.offsetWidth + lt +"px"});
                oResizeFileBtn.style.left=lt+'px';
            }
            document.onmouseup=function(){
                document.onmousemove=null;
                document.onmouseup=null;
                $("#MarkDownView").css({
                    'left':codeEditor.offsetWidth - 70 + oFileView.offsetWidth + 'px',
                    'top':Math.floor((codeEditor.offsetHeight - 40)/2) + 'px'
                });
                rendEditor($("#selectLanguage").val(),$("#selectTheme").val(),$("#selectFTsize").val());
            }
            return false;
        }

        var Toggle = 0;
        //显示测试视图
        $("#HideViewBtn").on('click',function(){
            if(Toggle%2 == 0){
                $("#HideViewBtn").text('>');
                $("#ResizeBtn").show();
                codeEditor.style.width = Math.floor(0.6 * WindowWidth) + 'px';
                oTestView.style.width = Math.floor(0.3 * WindowWidth) + 'px';
                oFileView.style.width = Math.floor(0.1 * WindowWidth) + 'px';
                $("#MarkDownView").css({'left':codeEditor.offsetWidth - 70 + oFileView.offsetWidth + 'px'});
                $("#ResizeBtn").css({'left':codeEditor.offsetWidth + oFileView.offsetWidth + 13 +"px"});
                $("#ResizeFileBtn").css({'left':oFileView.offsetWidth + 15 + "px"});
            }else{
                $("#HideViewBtn").text('<');
                $("#ResizeBtn").hide();
                codeEditor.style.width = Math.floor(0.8 * toolBar.offsetWidth) + 'px';
                oTestView.style.width = 0;
                oFileView.style.width = Math.floor(0.2 * toolBar.offsetWidth) + 'px';
                $("#MarkDownView").css({'left':codeEditor.offsetWidth - 70 + oFileView.offsetWidth + 'px'});
                $("#ResizeBtn").css({'left':codeEditor.offsetWidth + oFileView.offsetWidth + 13 +"px"});
                $("#ResizeFileBtn").css({'left':oFileView.offsetWidth + 15 + "px"});
            }
            rendEditor($("#selectLanguage").val(),$("#selectTheme").val(),$("#selectFTsize").val());
            Toggle += 1;
        });

        //运行
        $("#run").on("click", function(){
            if(Toggle%2 == 0){
                $("#HideViewBtn").click();
            }
        	$('#testViewIframe').attr('src', $('#testViewIframe').attr('src'));
        });
		//返回首页
        $("#BackToIndex").on('click',function(){
        	window.location.href = "{:url('index/index')}";
        });
		//保存代码
		$('#saveCode').on('click',function(){
			var code = editor.getValue();//获取代码
			var path = $("#nowFilePath").val();
			if(path != ''){
				$.post('./saveCode',{code:code,path:path},function(res){
					layer.msg(res.msg)
				});
			}
		});
		// ctrl+s保存屏蔽默认事件
		document.onkeydown=function (ev) {
			var oEvent = ev || event;
			if(oEvent.keyCode== 83 && oEvent.ctrlKey){
				oEvent.preventDefault()
				/*延迟，兼容FF浏览器  */
				setTimeout(function(){
					$("#saveCode").click();
				},1);
				return false;
			}
       };
    });
    </script>

<script type="text/javascript">
var nowNode = {'name':null,'children':null,'path':null,'type':null};
function getTree(){
	$('#tree').html('');
	$('#NewTree').html('');
	$('#DeleteTree').html('');
	$('#RenameTree').html('');
    layui.use('tree',function(){
        $.getJSON("{:url('Myfile/getMyFiles')}", function(res){
            if(111 == res.code){
                window.location.reload();
            }
            layui.tree({
                elem: '#tree'
                ,nodes: res.data
                ,click: function(node){
					if(nowNode.type == 'file'){
						$("#saveCode").click();
					}
                    var aCite = $('cite');
	                for(var i=0;i<aCite.length;i++){
	                	if(node.children.length == 0){
	                		if(aCite[i].innerHTML == node.name){
		                        aCite[i].parentNode.parentNode.style.backgroundColor = "#FFF";
		                        aCite[i].style.color = "#3D3E3F";
		                    }else{
		                        aCite[i].parentNode.parentNode.style.backgroundColor = '';
		                        aCite[i].style.color = "#a7b1c2";
		                    }
	                	}else{
	                		if(aCite[i].innerHTML == node.name){
		                        aCite[i].style.color = "#09F";
		                    }else{
		                        aCite[i].style.color = "#a7b1c2";
		                        aCite[i].parentNode.parentNode.style.backgroundColor = '';
		                    }
	                	}
	                }
	                if(node.type == 'file'){
						$("#nowFilePath").val(node.path);
						var language = node.path.split('.');
						language = language[language.length-1];
						switch (language) {
							case 'html':language = 'html';break;
							case 'php':language = 'php';break;
							case 'css':language = 'css';break;
							case 'js':language = 'javascript';break;
							default:language = 'text';break;
						}
						$('#selectLanguage').val(language);
		                $.post("./getFileConText",{path:node.path},function(res){
		                	var initCode = res.data;
					        var html = '<div id="editor"><textarea>'+initCode+'</textarea></div>';
					        codeEditor.innerHTML = html;
					        rendEditor(language,$("#selectTheme").val(),$("#selectFTsize").val());
	                    });
						// $('#testViewIframe').attr('src',node.path);
	            	}
					nowNode = node;
                }
            });
			var NewTreeData = [{
				'name':'我的文件夹',
				'path':'{$folder_path}',
				'children':res.data
			}]
			layui.tree({
				elem: '#NewTree',
				nodes: NewTreeData,
				click:function(node){
					$("#NewFloderPath").val(node.path);
					var param = $("#NewFolderForm").serialize();
					if($("#NewType").val() == 1){
						var url = "./NewFolder";
					}else{
						var url = "./NewFile";
					}
					$.post(url,param,function(res){
						if(res.code == 1){
							layer.closeAll();
							getTree();
						}
						layer.msg(res.msg);
					})
				}
			});
			layui.tree({
				elem: '#DeleteTree',
				nodes: res.data,
				click:function(node){
					if($("#DeleteType").val() == 1){
						var url = './DeleteFolder';
						var confirmMsg = '确认删除'+node.name+"及其所有子文件?"
					}else{
						var url = './DeleteFile';
						var confirmMsg = '确认删除'+node.name+"?"
					}
					layer.confirm(confirmMsg, {icon: 3, title:'提示'}, function(index){
						$.post(url,{path:node.path},function(res){
							if(res.code == 1){
								layer.closeAll();
								getTree();
							}
							layer.msg(res.msg);
						})
					})
				}
			});
			layui.tree({
				elem: '#RenameTree',
				nodes: res.data,
				click:function(node){
					$("#RenamePath").val(node.path);
					var param = $("#RenameForm").serialize();
					layer.confirm('确认重命名？', {icon: 3, title:'提示'}, function(index){
						$.post("./RenameFolder",param,function(res){
							if(res.code == 1){
								layer.closeAll();
								getTree();
							}
							layer.msg(res.msg);
						})
					})
				}
			});
        });
    });
}

$(function(){
	getTree();
})
//文件列表右键菜单
$(function(){
	var oFileView = document.getElementById('FileView');
	oFileView.oncontextmenu=function(ev){
		var oEvent = ev || event;
		oEvent.preventDefault();//取消默认的浏览器自带右键
		layer.open({
			type:1,
			title: false,
			closeBtn: false,
			shadeClose:true,
			area: '155px',
			id: 'ContTextMenu', //设定一个id，防止重复弹出
			content:$('#FileOncontextmenu'),
			offset:[oEvent.clientY+'px',oEvent.clientX+'px'],
		});
		return false;
	}

	// NewFolder
	$("#NewFolder").on('click',function(){
		layer.closeAll();
		$("#NewType").val(1);
		layer.open({
			type:1,
			title:'Which folder of your newly-buliding belongs to?',
			area:['450px','300px'],
			skin:'layui-layer-lan',
			content:$("#NewFolderAskBox"),
			btn:['Cancel'],
			yes:function(){
				layer.closeAll();
			}
		})
	});
	// NewFile
	$("#NewFile").on('click',function(){
		layer.closeAll();
		$("#NewType").val(0);
		layer.open({
			type:1,
			title:'Which folder of your newly-buliding belongs to?',
			area:['450px','300px'],
			skin:'layui-layer-lan',
			content:$("#NewFolderAskBox"),
			btn:['Cancel'],
			yes:function(){
				layer.closeAll();
			}
		})
	});
	// DeleteFolder
	$("#DeleteFolder").on('click',function(){
		$("#DeleteType").val(1);
		layer.closeAll();
		layer.open({
			type:1,
			title:'Which folder or file do you want to delete?',
			area:['450px','300px'],
			skin:'layui-layer-lan',
			content:$("#DeleteAskBox"),
			btn:['Cancel'],
			yes:function(){
				layer.closeAll();
			}
		})
	});
	// DeleteFile
	$("#DeleteFile").on('click',function(){
		$("#DeleteType").val(0);
		layer.closeAll();
		layer.open({
			type:1,
			title:'Which folder or file do you want to delete?',
			area:['450px','300px'],
			skin:'layui-layer-lan',
			content:$("#DeleteAskBox"),
			btn:['Cancel'],
			yes:function(){
				layer.closeAll();
			}
		})
	});
	// RenameFolderOrFile
	$("#RenameFolderOrFile").on('click',function(){
		layer.closeAll();
		layer.open({
			type:1,
			title:'Which folder or file do you want to Rename?',
			area:['450px','300px'],
			skin:'layui-layer-lan',
			content:$("#RenameAskBox"),
			btn:['Cancel'],
			yes:function(){
				layer.closeAll();
			}
		})
	});
})
</script>
{/block}
